import emitter from '#/utils/events';
import { useSize } from 'ahooks';
import * as echarts from 'echarts';
import { useEffect, useRef } from 'react';

export function EchartsComp({ config = {}, getRef = () => {} }) {
  let chartInstance = null;
  const chartRef = useRef(null);
  const chartSize = useSize(chartRef);

  const resizeHelper = () => {
    setTimeout(() => {
      chartInstance?.resize();
    }, 200);
  };
  function destoryed() {
    chartInstance?.dispose();
    window.removeEventListener('resize', resizeHelper);
    emitter.removeListener('onChangeMnue', resizeHelper);
  }

  function mounted() {
    window.addEventListener('resize', resizeHelper);
    emitter.addListener('onChangeMnue', resizeHelper);
    getRef(chartInstance);
  }

  function renderChart() {
    chartInstance = echarts.getInstanceByDom(chartRef?.current) || echarts.init(chartRef?.current);
    chartInstance?.setOption(config, true);
    chartInstance?.resize();
  }

  useEffect(() => {
    renderChart();
  }, [JSON.stringify(config)]);

  useEffect(() => {
    mounted();
    return () => {
      destoryed();
    };
  }, []);

  useEffect(() => {
    if (!chartSize?.width) return;
    renderChart();
  }, [chartSize]);

  return <div id="a" ref={chartRef} style={{ width: '100%', height: '100%' }} />;
}
